package com.lcu.wl.modules.tools.utils;

import com.lcu.wl.common.utils.SpringContextUtils;
import com.lcu.wl.modules.tools.entity.QuartzJob;
import com.lcu.wl.modules.tools.entity.QuartzLog;
import com.lcu.wl.modules.tools.service.IQuartzLogService;
import org.apache.commons.lang3.StringUtils;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.quartz.QuartzJobBean;

import java.lang.reflect.Method;
import java.util.Date;


/**
 * 定时任务
 */
public class ScheduleJob extends QuartzJobBean {
	private Logger logger = LoggerFactory.getLogger(getClass());

    @Override
    protected void executeInternal(JobExecutionContext context) throws JobExecutionException {
        QuartzJob quartzJob = (QuartzJob) context.getMergedJobDataMap()
        		.get(QuartzJob.JOB_PARAM_KEY);

        //获取spring bean
        IQuartzLogService iQuartzLogService = (IQuartzLogService) SpringContextUtils.getBean("quartzLogService");
        
        //数据库保存执行记录
        QuartzLog log = new QuartzLog();
        log.setJobId(quartzJob.getJobId());
        log.setBeanName(quartzJob.getBeanName());
        log.setParams(quartzJob.getParams());
        log.setCreateTime(new Date());

        //任务开始时间
        long startTime = System.currentTimeMillis();

        try {
            //执行任务
        	logger.debug("任务准备执行，任务ID：" + quartzJob.getJobId());

			Object target = SpringContextUtils.getBean(quartzJob.getBeanName());
			Method method = target.getClass().getDeclaredMethod("run", String.class);
			method.invoke(target, quartzJob.getParams());

			//任务执行总时长
			long times = System.currentTimeMillis() - startTime;
			log.setTimes((int)times);
			//任务状态    0：成功    1：失败
			log.setStatus(0);

			logger.debug("任务执行完毕，任务ID：" + quartzJob.getJobId() + "  总共耗时：" + times + "毫秒");
		} catch (Exception e) {
			logger.error("任务执行失败，任务ID：" + quartzJob.getJobId(), e);

			//任务执行总时长
			long times = System.currentTimeMillis() - startTime;
			log.setTimes((int)times);

			//任务状态    0：成功    1：失败
			log.setStatus(1);
			log.setError(StringUtils.substring(e.toString(), 0, 2000));
		}finally {
			iQuartzLogService.save(log);
		}
    }
}
